Laravel / Controller / File Uploading
File Uploading
-
STEP
In view
1. Add enctype="multipart/form-data" to form tag
2. method must be "POST"
3. add input type="file" for file browsing, name attribute is 'input_field_name'
Required class
use Illuminate\Support\Facades\File; Read the uploaded file from the http request
$request->file() is used for getting the uploaded file. Where $request is object of 'Request class' $imageObj = $request->file('input_field_name'); Save the file in the server
$imageObj->move() is used for storing the uploaded file in the server. Where $imageObj is object of 'Illuminate\Support\Facades\File class' $imageObj->move(public_path('/uploads'), $file_name); // first parameter is folder name, second parameter is file_name Complete code
To get file extensionnamespace App\Http\Controllers; use Illuminate\Support\Facades\File; class StudentController extends Controller { public function store(Request $request) { if ($request->hasFile('input_field_name')) { $imageObj = $request->file('input_field_name'); $file_name = $imageObj->getClientOriginalName() $imageObj->move(public_path('/uploads'), $file_name); } } } $file_name = $imageObj->getClientOriginalExtension(); To display the uploaded image in view blade
$company is object of 'App\Models\Company model'